﻿using GMS.NET.Application.Service.System.Extensions;
using GMS.NET.Application.Service.System.Topics;
using Microsoft.Extensions.Logging;
using MQTTnet.Protocol;
using MQTTnet.Server;

namespace GMS.NET.Application.Service.System.MqttNet
{
    public class MqttConnectionService : MqttServerBase, IMqttConnectionService
    {
        private readonly ILogger<MqttConnectionService> _logger;
        public MqttConnectionService(ILogger<MqttConnectionService> logger)
        {
            _logger = logger;
        }


        public override void ConfigureMqttServer(MqttServer mqttServer)
        {
            base.ConfigureMqttServer(mqttServer);

            mqttServer.ValidatingConnectionAsync += ValidatingConnectionHandlerAsync;
            mqttServer.ClientConnectedAsync += ClientConnectedHandlerAsync;
            mqttServer.ClientDisconnectedAsync += ClientDisconnectedHandlerAsync;
        }

        private Task ValidatingConnectionHandlerAsync(ValidatingConnectionEventArgs eventArgs)
        {
            if (eventArgs.ClientId == "SpecialClient")
            {
                if (eventArgs.UserName != "USER" || eventArgs.Password != "PASS")
                {
                    eventArgs.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                }
            }
            return Task.CompletedTask;
        }


        private async Task ClientConnectedHandlerAsync(ClientConnectedEventArgs eventArgs)
        {
            await MqttServer.PublishByHubAsync(BrokerTopics.Event.ConnectedClients, eventArgs.ClientId);
        }


        private async Task ClientDisconnectedHandlerAsync(ClientDisconnectedEventArgs eventArgs)
        {
            await MqttServer.PublishByHubAsync(BrokerTopics.Event.DisconnectedClients, eventArgs.ClientId);
        }
    }
}
